package com.lp.yupao.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lp.yupao.mapper.UserMapper;
import com.lp.yupao.model.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.lp.yupao.constant.RedisKey.CACHE_KEY;
import static com.lp.yupao.constant.RedisKey.RECOMMEND_KEY;

@Component
@Slf4j
public class PreCacheJob {
    // 核心用户信息
    private List<Long> mainUserList = Arrays.asList(1L);
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RedissonClient redissonClient;

    @Scheduled(cron = "0 39 * * * *")
    public void doCacheRecommendJob() {
        RLock lock = redissonClient.getLock(CACHE_KEY);
        try {
            boolean isLock = lock.tryLock(0, 10, TimeUnit.SECONDS);
            if (isLock) {
                // 执行业务
                for (Long userId : mainUserList) {
                    String redisKey = RECOMMEND_KEY + userId;
                    // 从数据库中查询用户
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userMapper.selectPage(new Page<>(1, 20), queryWrapper);
                    // 写缓存
                    try {
                        redisTemplate.opsForValue().set(redisKey, userPage, 30000, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.info("redis set error:" + e);
                        System.out.println("写入失败");
                    }
                }
            }
        } catch (InterruptedException e) {
            log.info("doCacheRecommendJob error" + e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                // 释放锁
                lock.unlock();
            }
        }
    }
}
